package guoTeng.netReadCard;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import com.invs.DeviceInfo;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Build.VERSION;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;


public class FindBtActivity extends Activity implements OnClickListener
{
	public static final String msg = "invs.blt";
	private boolean mBle = false;
    private boolean mScanning=false;

	private ListView listView;	
	MyAdapter adapter = new MyAdapter();
	private ArrayList<DeviceInfo> mDeviceInfoList = new ArrayList<DeviceInfo>();    
    
	private BluetoothManager mBltManager ; 
	private BluetoothAdapter mBltAdapter ;
	private LeScanCallback mScanCallback ; 
	private BroadcastReceiver mReceiver;
	
    public void scanDevice(boolean ble, boolean enable) {	
    	if (ble){
    		scanDevice4(enable);
    	}else{
    		scanDevice2(enable);
    	}
    }
    
    int Cmd_ScanDev = 2;
	void addDev(BluetoothDevice device){
		DeviceInfo dev = new DeviceInfo();
		dev.name = device.getName();
		dev.address = device.getAddress();
		
        Intent devIntent = new Intent();  
        devIntent.setAction(msg);  
        devIntent.putExtra("cmd", Cmd_ScanDev);                      
        devIntent.putExtra("DeviceInfo", dev);  
        sendBroadcast(devIntent);    
	}
	    
    public boolean initialize4() {
        mBltManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (mBltManager == null) {
            return false;
        }

        mBltAdapter = mBltManager.getAdapter();
        if (mBltAdapter == null) {
            return false;
        }

        if (!mBltAdapter.isEnabled()){
        	mBltAdapter.enable();
        }
                
        return true;
    }
    

	public void initCallback4(){
        mScanCallback  = new LeScanCallback() {
            @Override
            public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
	            try{            	
	        		addDev(device);
	    		} catch (Exception e) {
	    		}	
            }
        };
    }
    
	public void scanDevice4(final boolean enable) {
    	try{
	    	if (!initialize4()){
	    		return;
	    	}
	    	if (mScanCallback == null){
	    		initCallback4();
	    	}
	        if (enable) {
	        	mBltAdapter.startLeScan(mScanCallback);
	        } else {
	            mBltAdapter.stopLeScan(mScanCallback);
	        }
    	} catch (Exception e) {  
    		
        }  
    }

    public boolean initialize2() {
    	mBltAdapter = BluetoothAdapter.getDefaultAdapter();
    	if (mBltAdapter == null) {
    		return false;
    	}
    	
        if (!mBltAdapter.isEnabled()){
        	mBltAdapter.enable();
        } 

        return true;
    }
    
	public void initCallback2(){
		 mReceiver = new BroadcastReceiver() {  
		        @Override  
		        public void onReceive(Context context, Intent intent) {  
		            String action = intent.getAction();  
		            if (action.equals(BluetoothDevice.ACTION_FOUND)) {  
		                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
		                int sysVersion = Integer.parseInt(VERSION.SDK);
		                if (sysVersion >= 18){
		    	            if (device.getType() != BluetoothDevice.DEVICE_TYPE_CLASSIC){
		    	    			return;
		    	    		}
		                }
		                
		                addDev(device);
		            } 
		        }  
		    };  
	}
	
	public void scanDevice2(final boolean enable) {
    	if (!initialize2()){
    		return;
    	}
    	
    	if (mReceiver == null){
    		initCallback2();
    	}
    	
        if (enable) {
            
            IntentFilter intent = new IntentFilter();   
            intent.addAction(BluetoothDevice.ACTION_FOUND);
            try{
            	registerReceiver(mReceiver, intent); 
            	mBltAdapter.startDiscovery();
            } catch (Exception e) {  
  
            } 
        } else {
        	mBltAdapter.cancelDiscovery();
            try {  
            	unregisterReceiver(mReceiver);
            } catch (Exception e) {    
            }  
        }
    }
    
	public void onClick(View v) {	
		Button b;
		switch(v.getId()){
		case R.id.button1:
	        b = (Button) findViewById(R.id.button1);
	        b.setEnabled(false);
	        b = (Button) findViewById(R.id.button2);	        
	        b.setEnabled(true);

			setProgressBarIndeterminateVisibility(true);
			scan(true);
			break;
		case R.id.button2:
	        b = (Button) findViewById(R.id.button1);
	        b.setEnabled(true);
	        b = (Button) findViewById(R.id.button2);
	        b.setEnabled(false);
	        
			setProgressBarIndeterminateVisibility(false);
			scan(false);
			break;
		case R.id.button3:
			SharedPreferences sp = getSharedPreferences("BindDevice", Activity.MODE_PRIVATE);
			String s = sp.getString("Address", "");
			break;
		}
	}
	
    void scan(boolean enable){
    	if (enable){
    		mDeviceInfoList.clear();
    		listView.setAdapter(new MyAdapter());  
    		
        	RadioButton r = (RadioButton)findViewById(R.id.radioBtn1);
        	r.setEnabled(false);  
        	r = (RadioButton)findViewById(R.id.radioBtn2); 
        	r.setEnabled(false);
        	if (r.isChecked()){
        		mBle = true;
        	}else{
        		mBle = false;
        	}
    	}else{
    		//stopTimer();
        	RadioButton r = (RadioButton)findViewById(R.id.radioBtn1); 
        	r.setEnabled(true);  
        	if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
	        	r = (RadioButton)findViewById(R.id.radioBtn2); 
	        	r.setEnabled(true);    		
        	}
    	}
    	mScanning = enable;
    	scanDevice(mBle, enable);
    }
    
    
	void SetSelDev(){
		SharedPreferences sp = getSharedPreferences("BindDevice", Activity.MODE_PRIVATE);
		String szAddress = sp.getString("Address", "");
		String szName = sp.getString("Name", "");
		boolean ble = sp.getBoolean("bleAddress", true); 
		
		TextView v = (TextView)findViewById(R.id.tv1);
		
		if (szAddress == null || szAddress == "") {		
			v.setText("no dev");
		}else{
			if (ble){
				v.setText("last 4.0 dev is:"+szName+"\n                          "+szAddress);
			}else{
				v.setText("last 2.0 dev is:"+szName+"\n                          "+szAddress);
			}
		}		
	}
    
    RadioGroup raGroup1; 
    void initRadioBtn(){
    	raGroup1=(RadioGroup)findViewById(R.id.radioGroup1);       
        raGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {  
              
            @Override 
            public void onCheckedChanged(RadioGroup group, int checkedId) {  
        		mDeviceInfoList.clear();
        		listView.setAdapter(new MyAdapter());  
                if(checkedId==R.id.radioBtn1){                  	
                	mBle = false;		        	
                } else if(checkedId==R.id.radioBtn2){ 
                	mBle = true;             	
                }
            }  
        });
    }
    
    void checkBltMod(){
    	if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
        	RadioButton r = (RadioButton)findViewById(R.id.radioBtn1); 
        	r.setEnabled(false);
        	r.setChecked(true);
        	r = (RadioButton)findViewById(R.id.radioBtn2); 
        	r.setEnabled(false);
        	r.setVisibility(0x00000008);
    	}else{
    		SharedPreferences sp = getSharedPreferences("BindDevice", Activity.MODE_PRIVATE);
    		boolean ble = sp.getBoolean("bleAddress", true);    	
	    	if (ble){
	    		RadioButton r = (RadioButton)findViewById(R.id.radioBtn2); 
	    		r.setChecked(true);
	    		r = (RadioButton)findViewById(R.id.radioBtn1); 
	    		r.setVisibility(0x00000008);
	    	}else{
	    		RadioButton r = (RadioButton)findViewById(R.id.radioBtn1); 
	    		r.setChecked(true);	  
	    	}
    	}
    }
    
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.findbt);
		
		regRecv();
		
		checkBltMod();
		
		SetSelDev();
		
		listView = (ListView) this.findViewById(R.id.list);
		listView.setAdapter(adapter);
			
		initRadioBtn();
		
        Button b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(this);		
        
        b = (Button) findViewById(R.id.button2);
        b.setOnClickListener(this);	
        b.setEnabled(false);
        
        b = (Button) findViewById(R.id.button3);
        b.setOnClickListener(this);	
        b.setVisibility(8);
        //b.setEnabled(false);
	}
	
	private class MyAdapter extends BaseAdapter{
		private int temp = -1;

		public int getCount() {
		// TODO Auto-generated method stub
			return mDeviceInfoList.size();
		}
	
		public Object getItem(int position) {
			return mDeviceInfoList.get(position);
		}
	
		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			try{
			convertView = FindBtActivity.this.getLayoutInflater().inflate(R.layout.item, null); 
			TextView tv = (TextView) convertView.findViewById(R.id.tv);
			
			DeviceInfo info = mDeviceInfoList.get(position);
			if (info != null) {  
				tv.setText(info.name + "\n" + info.address);
				RadioButton radioButton = (RadioButton) convertView.findViewById(R.id.radioButton);
				
				radioButton.setId(position); 			
				radioButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						try{
						if(isChecked){
							int i = temp;
							if(temp != -1){
								RadioButton tempButton = (RadioButton) FindBtActivity.this.findViewById(temp);
								if(tempButton != null && temp != buttonView.getId()){
									tempButton.setChecked(false);
								}						
							}
								
							temp = buttonView.getId();
							i = temp;
							
							DeviceInfo info = mDeviceInfoList.get(temp); 
					    	SharedPreferences sp = getSharedPreferences("BindDevice", Activity.MODE_PRIVATE);
				        	SharedPreferences.Editor edit = sp.edit();	        	
				        	edit.putString("Name", info.name);
				        	edit.putString("Address", info.address);
				        	edit.putBoolean("bleAddress", mBle);
				        	edit.commit();						
						}else{
							
						}
						} catch (Exception e) {
						}
					}
				});
				
	    		SharedPreferences sp = getSharedPreferences("BindDevice", Activity.MODE_PRIVATE);
	    		String szAddress = sp.getString("Address", "");	
	    		
				if (info.address.equalsIgnoreCase(szAddress)){
					radioButton.setChecked(true);
				}
	
				/*
				if(temp == position){
					radioButton.setChecked(true);
				}*/
			}
			} catch (Exception e) {
				return null;
			}
			return convertView;
		}
	}
	
	void regRecv()
	{
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(msg);	
		registerReceiver(mUpdate, intentFilter);
	}
		
    private final BroadcastReceiver mUpdate = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
		try{
            if (!msg.equals(intent.getAction())) {
            	return;          	
            }
            
           	DeviceInfo dev = (DeviceInfo) intent.getSerializableExtra("DeviceInfo"); 
        	           
           	if (dev.name == null || dev.name == ""){
           		return;
           	}
           	/*
    		if (dev.name.indexOf("INVS300-") != 0 && dev.name.indexOf("CDINVS300-") != 0){ 
    			return;    			
    		}
    		*/
      		for (int i=0; i<mDeviceInfoList.size(); i++){  
    			if (dev.address.equalsIgnoreCase(mDeviceInfoList.get(i).address)){
    				return;
    			}
    		}   		
    		mDeviceInfoList.add(dev);
    		Collections.sort(mDeviceInfoList, new DeviceInfo.ComparatorValues());
    		listView.setAdapter(new MyAdapter());     
        } catch (Exception e) {
		}
        }
    };	

    @Override
    protected void onDestroy() {
    	scan(false);
    	super.onDestroy();
    }   
}
